<?php

/**
 * CodeRS - Atviras kodas Lietuvai
 * Copyright (C) 2007 CodeRS www.coders.lt info@coders.lt
 * MightMedia TVS
 * pm.php - vartotojo laiškų dėžutė.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 * 
 * Ši programa yra laisva. Jūs galite ją platinti ir/arba modifikuoti
 * remdamiesi Free Software Foundation paskelbtomis GNU Bendrosios
 * Viešosios licencijos sąlygomis: 2 licencijos versija, arba (savo
 * nuožiūra) bet kuria vėlesne versija.
 * 
 * Ši programa platinama su viltimi, kad ji bus naudinga, bet BE JOKIOS
 * GARANTIJOS; be jokios numanomos PERKAMUMO ar TINKAMUMO KONKRETIEMS
 * TIKSLAMS garantijos. Žiūrėkite GNU Bendrąją Viešąją licenciją norėdami
 * sužinoti smulkmenas.
 * 
 * Jūs turėjote kartu su šia programa gauti ir GNU Bendrosios Viešosios
 * licencijos kopija; jei ne - rašykite Free Software Foundation, Inc., 59
 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
**/

if ($_SERVER['PHP_SELF'] == __FILE__) { header('location: ?'); exit(); }

if (!PRISIJUNGES) { header("Location: /"); exit(); }

if (isset($url['u']) && !empty($url['u'])) { $uid = input($url['u']); }
if (isset($url['i']) && isnum($url['i']) && $url['i'] > 0) { $pid = (int) $url['i']; } else { $pid = 0; } //kam atsakom
if (isset($url['d']) && isnum($url['d'])) $del = (int) $url['d']; //ka trinam?
if (isset($url['p']) && isnum($url['p']) && $url['p'] > 0) { $p = (int) $url['p']; } else { $p = 0; } //puslapiavimas
if (isset($url['a']) && isnum($url['a']) && $url['a'] >= 0) { $a = (int) $url['a']; } else { $a = 1; } //inbox arba outbox
if (isset($url['o']) && !empty($url['o'])) { $order = input($url['o']); } else { $order = 'date'; }	//lygiavimas
if (isset($url['s']) && !empty($url['s'])) { $s = input($url['s']); } //paieska
switch ($order) {
	case "Kada:":
		$order = "date";
	break;
	case "Siunt%C4%97jas:":
		$order = "from";
	break;
	case "Tema:":
		$order = "title";
	break;
	default:
		$order = "date";
	break;
}
$limit = 30;
$pm_sk = $db->kiek_irasu("`private_msg` WHERE `to`='".$db->fix($ses->user_data['username'])."'");

//
// DELETE PM (or pms)
//
if (isset($del)) {
	if ($del == 0) {
		$db->uzklausa("DELETE FROM `private_msg` WHERE `to`='".$db->fix($ses->user_data['username'])."'");
		header("Location: ?id,45;p,".$p."");
	} else {
		$db->uzklausa("DELETE FROM `private_msg` WHERE `to`='".$db->fix($ses->user_data['username'])."' AND `id`='".$del."'");
		header("Location: ?id,45;p,".$p."");
	}
}

//
// SENDING PM
//
if (isset($_POST['action']) && $_POST['action'] == 'pm_send') {
	$title = input($_POST['title']);	if (!isset($title)) $title = "[Be Pavadinimo]";

	$sql = $db->uzklausa("SELECT * FROM `".T_USERS."` WHERE `username`='".$db->fix(input($_POST['to']))."'");
	if ($db->rows($sql) == 0) {
		msg("DĖMESIO!", "Vartotojas kurį įvedėte neegzistuoja");
	} else {
		if ($db->kiek_irasu("`private_msg` WHERE `to`='".$db->fix(input($_POST['to']))."'") < 100) {
			if ($db->uzklausa("INSERT INTO `private_msg` SET `from`='".$db->fix($ses->user_data['username'])."', `to`='".$db->fix(input($_POST['to']))."',
`title`='".$db->fix($title)."', `msg`='".$db->fix($_POST['msg'])."', `read`='0', `date`='".date("Y-m-d H:i:s")."'", __FILE__, __LINE__)) {
				msg("Sėkmingai", "Jūsų žinutė išssiųsta vartotojui <b>".$to."</b>");
				redirect("?id,45", "header");
			} else msg("DĖMESIO!", "Jūsų žinutė neišsiųsta");
		} else { 			
			$sql = $db->masyvas($sql); //$result = $db->uzklausa("INSERT INTO `private_msg` (`from`, `to`, `title`, `msg`, `read`, `date`) VALUES ('" . $db->fix($conf['Pavadinimas']) ."', '" . $db->fix($to) ."', '" . $db->fix("Jūsų pašto dėžutė pilna") ."', " . escape("Jūsų pašto dėžutė užsipildė. Kiti svetainės lankytojai jums nebegali siųsti žinučių.") .", 'NO', '" . $date ."')");
			klaida("Klaida","Vartotojo <b>".$to."</b> dėžutė pilna. Parašykite jam elektroninį laišką adresu ".preg_replace("#([a-z0-9\-_.]+?)@([\w\-]+\.([\w\-\.]+\.)?[\w]+)#i", "<a href=\"javascript:mailto:mail('\\1','\\2');\">\\1_(at)_\\2</a>", $sql['email'])."");
			redirect("?id,45","meta"); 
		}
	}
}
///
// Bloko rodymas ir žinučių išvedimas
//
$text = "
<fieldset>
<legend>Laisva vieta</legend>
<table border=0>
	<tr>
		<td>
		Liko: <b>" . ($ses->user_data['pm_viso'] - $pm_sk) . "</b><br />
		Išnaudota <b>" . $pm_sk ."</b> iš <b>" . $ses->user_data['pm_viso'] ."</b><br />";
$pm_img = substr($pm_sk, 0, -1);
$pm_img = "<img src='images/pm/".(empty($pm_img) ? '0' : $pm_img).".gif'/>";
$text .= $pm_img ."
		</td>
	</tr>
	<tr>
		<td></td>
	</tr>
</table>
</fieldset>

<fieldset>
<legend>Privačių žinučių veiksmai</legend>
	<table width='100%'>
		<tr>
			<td>
				<div class=\"blokas\"><center><a href='?id,45;n,1'><img src=\"images/pm/new.png\" alt=\"nauja\" />Rašyti</a></center></div>
				<div class=\"blokas\"><center><a href='?id,45'><img src=\"images/pm/inbox.png\" alt=\"inbox\" />Gautos</a></center></div>
				<div class=\"blokas\"><center><a href='?id,45;a,0'><img src=\"images/pm/outbox.png\" alt=\"outbox\" />Išsiųstos</a></center></div>
				<div class=\"blokas\"><center><a href='?id,45;s,1'><img src=\"images/pm/search.png\" alt=\"outbox\" />Paieška</a></center></div>
				<div class=\"blokas\"><center><a href='?id,45;d,0' onclick=\"return confirm('Ar tikrai ištrinti visas žinutes?')\"><img src=\"images/pm/delete_all.png\" alt=\"trinti\" />Trinti viską</a></center></div>
				<div class=\"blokas\"><center><a href='http://code.google.com/p/mightmedia/wiki/pm' target=\"_blank\"><img src=\"images/pm/help.png\" alt=\"Pagalba\" />Pagalba</a></center></div>
			</td>
		</tr>
	</table>
 </fieldset>";

//
// VIEW A PM
//
if (isset($url['v'])) {
	if(!empty($url['v']) && (int)$url['v'] > 0 && isnum($url['v'])) {
		$sql = $db->masyvas($db->uzklausa("SELECT `msg`, `from`, `title` FROM `private_msg` WHERE `to`='".$db->fix($ses->user_data['username'])."' AND id='".$db->fix($url['v'])."'"));
		if ($sql) {
			$text .= "
				<fieldset>
				<legend>Privačios žinutės tekstas:</legend>
				<table border='0' width='100%'>
					<tr>
						<td class=\"title\" align=\"left\">Nuo: " . $sql['from'] ." Tema: ".input($sql['title'])."</td>
					</tr>
					<tr>
						<td width=\"50%\"  class=\"sarasas\" style=\"background-color: #FFFFCC\"><div align=\"justify\"><p>" . bbcode($sql['msg']) ."</p></div></td>
					</tr>
				</table>
				<form name=\"replay_pm\" action='?id,45;n,1;u," . $sql['from'] .";i," . $url['v'] ."' method=\"post\">
					<input type=\"submit\" value=\"Atsakyti\"/> <input type=\"button\" value=\"Trinti\" onclick=\"location.href='".url("d,".$url['v']."")."'\"/>
				</form>
				</fieldset>
			";
			$db->uzklausa("UPDATE `private_msg` SET `read`='YES' WHERE `id`='".$db->fix($url['v'])."' AND `to`='".$db->fix($ses->user_data['username'])."'");
		}
	}
}

// ################### Siusti nauja zinute arba atsakyti i esancia ######################################
if (isset($url['n'])) {
	if (!empty($url['n']) && (int)$url['n']) {
		// ############### Jei nera paspaustas atsakyti mygtukas sukuriam paprasta forma #################
		//if ((int)$pid == 0) {
			$sql1 = $db->uzklausa("SELECT `nick` FROM users WHERE `nick` <> '".$db->fix($ses->user_data['username'])."' ORDER BY nick ASC");
			if (isset($error) && !empty($error)) { msg("Dėmesio!",$error); }
			if (isset($uid) && (int)$pid > 0) {
				$sql = $db->masyvas($db->uzklausa("SELECT * FROM `private_msg` WHERE `from`='".$db->fix($uid)."' AND `id`='".$db->fix($pid)."'"));
			}
			$text .= "
				<fieldset>
				<legend>".((isset($uid) && (int)$pid > 0)?"Atsakyti":"Siųsti")." privačia žinutę</legend>
				<form name=\"msg\" action=\"?id,45;\" method=\"post\">
					<table border=0 width=\"100%\">
					<tr>
						<td width=\"15%\" class=\"sarasas\">Gavėjas:</td>
						<td>
							<select size=\"1\" name=\"to\">
			";
			while($row = $db->masyvas($sql1)) {
				$text .= "<option value=\"" . $row['nick'] ."\" ";
				if (isset($uid) && strtolower($row['nick']) == strtolower($uid)) { $text .= "selected=\"selected\""; }
				$text .= ">" . $row['nick'] ."</option>";
			}
			$text .= "
							</select>
						</td>
					</tr>
					<tr>
						<td class=\"sarasas\">Tema:</td>
						<td><input name=\"title\" type=\"text\" size=\"50\" value=\"".((isset($uid) && (int)$pid > 0)?"Re: " . $sql['title']:"Siųsti")."\" style=\"width:95%\"></td>
					</tr>
					<tr>
						<td valign='top' align='left' class=\"sarasas\">Žinutė:</td>
						<td><textarea name=\"msg\" rows=\"20\" cols=\"50\" wrap=\"on\" style=\"width:95%\">".((isset($uid) && (int)$pid > 0)?"[quote=" . $uid ."]" . input(trim(preg_replace(array("#\[quote=(http://)?(.*?)\](.*?)\[/quote]#si","[/quote]"),"",$sql['msg']))) ."[/quote]\n\n":"")."</textarea>
						<br />
						".bbk("msg")."
						<br />
						<input type=\"submit\" value=\"".((isset($uid) && (int)$pid > 0)?"Atsakyti":"Siųsti")."\">
						<input type=\"hidden\" name=\"action\" value=\"pm_send\" />
					</td>
					</tr>
					</table>
				</form>
			</fieldset><script>addText('msg', '', '');</script>
			";
		//}
	}
	else { header("Location: ?"); }
}

lentele("Privačių žinučių valdymas",$text);

if (defined("LEVEL") && LEVEL > 0 && $a == 1 && !isset($s)) {
	include("variklis/class.php");
	$sql = $db->uzklausa("SELECT `id`, `read`, IF(`from` = '', 'Svečias',`from`) AS `Nuo`, INSERT(LEFT(`msg`,80),80,3,'...') AS `Žinutė`, IF(`title` = '', 'Be pavadinimo',INSERT(LEFT(`title`,80),80,3,'...')) AS `Pavadinimas`, `date` AS `Data` FROM `private_msg` WHERE `to`='".$db->fix($ses->user_data['username'])."' ORDER BY `private_msg`.`$order` DESC LIMIT $p,$limit") or die(mysql_error());
	if ($db->rows($sql) > 0) {
		$bla = new Table();
		$info = array();
		while($row = $db->masyvas($sql)) {
			if ($row['read'] == "NO") {
				$extra ="<img src='images/pm/pm_new.png' />";
			} else {
				$extra = "<img src='images/pm/pm_read.png' />";
			}
			$info[]=array(
			""=> $extra,
			"Tema:"=>"<a href='?id,45;v,".$row['id']."' style=\"display: block\">".input($row['Pavadinimas'])."</a></div>",
			"Siuntėjas:"=>"<a href='?id,47;m,51' style=\"display: block\" title=\"header=[".$row['Nuo']."] body=[<br/>Data: <b>".$row['Data']."</b><br/>Kada: <b>".kada($row['Data'])."</b><br/>Žinutė: <i>".nl2br(strip_tags(input(str_replace(array("[","]"),"",$row['Žinutė']))))."</i><br/>] cssbody=[sarasas] cssheader=[title] fade=[on]\">".$row['Nuo']."</a>",
			"Kada:"=>kada($row['Data']),
			" "=>"<a href='?id,45;n,1;u," . $row['Nuo'] .";i,".$row['id']."'><img src='images/pm/replay.png' border=0 alt=\"Atsakyti\" title=\"Atsakyti\"/></a><a href='".url('d,'.$row['id'].'')."'><img src='images/pm/delete.png' border=0 alt=\"Trinti\" title=\"Trinti\"/></a>"
			);
		}
		//asort($info);
		lentele("Gautos žinutės",puslapiai($p,$limit,$pm_sk,10)."<br/>".$bla->render($info)."<br/>".puslapiai($p,$limit,$pm_sk,10));
	}
	else { klaida("Klaida","Laiškų nėra"); }
}
if (defined("LEVEL") && LEVEL > 0 && $a == 0 && !isset($s)) {
	include("dievai/class.php");
	$sql = $db->uzklausa("SELECT `id`, `read`, IF(`to` = '', 'Svečias',`to`) AS `to`, INSERT(LEFT(`msg`,80),80,3,'...') AS `Žinutė`, IF(`title` = '', 'Be pavadinimo',INSERT(LEFT(`title`,80),80,3,'...')) AS `Pavadinimas`, `date` AS `Data` FROM `private_msg` WHERE `from`='".$db->fix($ses->user_data['username'])."' ORDER BY `private_msg`.`$order` DESC LIMIT $p,$limit") or die(mysql_error());
	if ($db->rows($sql) > 0) {
		$bla = new Table();
		$info = array();
		while($row = $db->masyvas($sql)) {
			if ($row['read'] == "NO") {
				$extra ="<img src='images/pm/pm_new.png' />";
			} else {
				$extra = "<img src='images/pm/pm_read.png' />";
			}
			$info[]=array(
			""=> $extra,
			"Tema:"=>"<a href='?id,45;v,".$row['id']."' style=\"display: block\">".input($row['Pavadinimas'])."</a>",
			"Gavėjas:"=>"<a href='?id,47;m,51' style=\"display: block\" title=\"header=[".$row['to']."] body=[<br/>Data: <b>".$row['Data']."</b><br/>Kada: <b>".kada($row['Data'])."</b><br/>Žinutė: <i>".nl2br(strip_tags(input(str_replace(array("[","]"),"",$row['Žinutė']))))."</i><br/>] cssbody=[sarasas] cssheader=[title] fade=[on]\">".$row['to']."</a>",
			"Kada:"=>kada($row['Data'])
			);
		}
		asort($info);
		lentele("Išsiųstos žinutės",puslapiai($p,$limit,$pm_sk,10)."<br/>".$bla->render($info)."<br/>".puslapiai($p,$limit,$pm_sk,10),"Laiškų dėžutė");
	}
	else { klaida("Klaida","Laiškų nėra"); }
}
elseif (isset($s)) { klaida("Klaida","Ši dalis dar nėra suprogramuota"); }
?>
